<template>
  <van-button
    v-if="isFollowed"
    class="follow-btn"
    round
    size="small"
    :loading="followLoading"
    @click="changeIsFollowWithLoding"
    >已关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    :loading="followLoading"
    @click="changeIsFollowWithLoding"
    >关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from '@/api/article/article.js'
export default {
  name: 'FollowedBtn',
  data() {
    return {
      followLoading: false
    }
  },
  created() {},
  props: {
    articleDetail: {
      type: Object,
      required: true
    }
  },
  methods: {
    async doFollow() {
      this.followLoading = true
      // 取关，调用取关接口
      try {
        await addFollow(this.articleDetail.aut_id)
        this.articleDetail.is_followed = true
        this.$toast.success('关注成功')
      } catch (error) {
        if (error.response && error.response.status === 400) {
          return this.$toast.fail('不能关注自己')
        }
        this.$toast.fail('服务器繁忙')
      }
      this.followLoading = false
    },
    async cancelFollow() {
      this.followLoading = true
      // 取关，调用取关接口
      try {
        await deleteFollow(this.articleDetail.aut_id)
        this.articleDetail.is_followed = false
        this.$toast.success('取关成功')
      } catch (error) {
        this.$toast.fail('服务器繁忙')
      }
      this.followLoading = false
    },
    changeIsFollowWithLoding() {
      this.isFollowed ? this.cancelFollow() : this.doFollow()
    }
  },
  computed: {
    isFollowed() {
      return this.articleDetail.is_followed
    }
  },
  watch: {},
  components: {}
}
</script>

<style lang="less" scoped>
.followed {
  color: orange;
}
</style>
